package main

import (
	"ce-cloud-service/internal/proto/base/user"
	"ce-cloud-service/internal/services/base/user/db/impl"
	"ce-cloud-service/internal/services/base/user/db/model"
	"ce-cloud/pkg/data_source/d_cache"
	"ce-cloud/pkg/log"
	"context"
	"encoding/json"
	"fmt"
	"time"
)

type UserService struct {
}

func (u *UserService) makeUserOnlineKey(userId int64) string {
	return fmt.Sprintf("user_online:%d", userId)
}

func (u *UserService) UserRegister(_ context.Context, request *user.UserRegisterRequest, response *user.UserRegisterResponse) error {
	timeNow := time.Now().Unix()
	err := impl.NewUserImpl().Create(model.User{
		Account:  request.Account,
		NickName: request.Nickname,
		Password: request.Password,
		State:    0,
		CreateAt: timeNow,
		UpdateAt: timeNow,
		DeleteAt: 0,
	})
	if err != nil {
		return err
	}
	newData, err := impl.NewUserImpl().Get(model.User{Account: request.Account})
	if err != nil {
		return err
	}
	response.UserId = newData.Uid
	userInfo, _ := json.Marshal(newData)
	d_cache.Cache.SetWithTTL(u.makeUserOnlineKey(newData.Uid), string(userInfo), 30)
	return nil
}

func (u *UserService) UserLogin(ctx context.Context, request *user.UserLoginRequest, rsp *user.UserLoginResponse) error {
	data, err := impl.NewUserImpl().Get(model.User{Account: request.Account, Password: request.Password})
	if err != nil {
		log.Errorf("user login get user error:%+v", err)
		return err
	}
	rsp.UserId = data.Uid
	rsp.Token = "" //在网关部分做了返回
	return err
}
